package com.wan37.client.message.received;

import com.google.protobuf.Message;
import com.googlecode.protobuf.format.JsonFormat;
import com.wan37.client.handler.ClientHandler;
import com.wan37.client.service.cache.RoleServiceCache;
import com.wan37.client.service.cache.UserServiceCache;
import com.wan37.protobuf.constant.Common;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.client2server.game.Game;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 初始化或者切换场景使用将会把全部场景用户修改
 *
 * @author : luoyong
 * @date : 2020-07-01 16:16
 **/
@Component(PtoNum.SGAMEROLERESPONSE + "")
public class SGameRoleResponse implements ReceiveMsg {

    private final static Logger logger = LoggerFactory.getLogger(SGameRoleResponse.class);
    @Autowired
    private UserServiceCache userServiceCache;
    @Autowired
    private RoleServiceCache roleServiceCache;
    private ClientHandler clientHandler = ClientHandler.getInstance();

    @Override
    public void execute(Message msg) {
        Game.SGameRoleResponse sGameRoleResponse = (Game.SGameRoleResponse) msg;
        int code = sGameRoleResponse.getCode();
        if (code == Common.GAME_ROLE_SUCCESS) {
            //进入新场景清空原来的用户缓存和角色缓存相关数据
            roleServiceCache.getRoleInMap().clear();
            userServiceCache.getUserInMap().keySet().removeIf(s -> !s.equals(clientHandler.selfId));
            logger.info("用户角色已获取成功！！！");
            System.out.println("当前用户角色的更新情况：");
            sGameRoleResponse.getUserIdToRoleList().forEach(userIdToRole -> {
                String userId = userIdToRole.getUserId();
                List<String> roleIdList = new ArrayList<>();
                userIdToRole.getRoleList().forEach(role -> {
                    String roleId = role.getAllRole().getAllRoleId();
                    RoleServiceCache.RoleIn roleIn = roleServiceCache.new RoleIn();
                    roleIn.setRole(role);
                    roleIdList.add(roleId);
                    roleServiceCache.getRoleInMap().put(roleId, roleIn);
                    System.out.println(role.getAllRole().getAllRoleId() + ":" + JsonFormat.printToString(role));
                });
                if (!userServiceCache.getUserInMap().containsKey(userId)){
                    UserServiceCache.UserIn userIn = userServiceCache.new UserIn();
                    userServiceCache.getUserInMap().put(userId, userIn);
                }
                userServiceCache.getUserInMap().get(userId).setRoleIdList(roleIdList);
            });
        }
    }
}
